package com.loan.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.loan.enums.InvestLogType;
import com.loan.enums.S;
import com.loan.model.Data;
import com.loan.model.Loan;
import com.loan.model.Repay;
import com.loan.model.User;
import com.loan.service.InvestLogService;
import com.loan.service.LoanService;
import com.loan.service.RepayService;
import com.loan.util.DateUtil;
import com.loan.util.Json;
import com.loan.util.Money;
import com.loan.util.Str;

/**
 *  用户控制器
 * @since 2018-03-03
 * @author 无处不在的二叔
 */ 
public class LoanController extends Controller {
	private static LoanService loan = new LoanService();
	private static RepayService repay = new RepayService();

	/**  
	 * 新增贷款记录
	 * @throws Exception 
	 */
	public void index() throws Exception { 
		User u = getAttr("user");
		if(u.getIsPhoneBook()==1&& Str.ne(S.WAITING, u.getInfoVerifyStatus()) && Str.ne(S.WAITING, u.getCardVerifyStatus()) 
			&& Str.ne(S.WAITING, u.getCardVerifyStatus())  && Str.ne(S.WAITING, u.getServiceVerifyStatus())){
			
			// 判断是否已有进行中的订单
			if(loan.findProcess(u.getId())==null) {
				Loan ln = new Loan(); 
				ln.setUserId(u.getId()); 
				ln.setMobile(u.getMobile());
				ln.setCode(DateUtil.getTimeStamp());
				ln.setPhone(getPara("phone"));
				ln.setStatus(S.VERIFY);
				ln.setSystem(getPara("system"));
				ln.setRealName(u.getRealName());
				ln.setCreateTime(new Date()); 
				ln.setMobile(u.getMobile());
				ln.setCid(u.getCid());
				ln.setDay(getParaToInt("day"));
				
				switch(ln.getPhone()) {
					/**case "iPhone 6":ln.setAmount(1000).setPledge(200).setInterest(350);break;
					case "iPhone 6s":ln.setAmount(1000).setPledge(200).setInterest(350);break;
					case "iPhone 6 plus":ln.setAmount(1200).setPledge(240).setInterest(420);break;
					case "iPhone 6s plus":ln.setAmount(1200).setPledge(240).setInterest(420);break;
					case "iPhone 7":ln.setAmount(1500).setPledge(300).setInterest(525);break;
					case "iPhone 7 plus":ln.setAmount(1500).setPledge(300).setInterest(525);break;
					case "iPhone 8":ln.setAmount(2000).setPledge(400).setInterest(700);break;
					case "iPhone 8 plus":ln.setAmount(2200).setPledge(440).setInterest(770);break;
					case "iPhone X":ln.setAmount(2500).setPledge(500).setInterest(875);break;*/
					default:ln.setAmount(1000).setPledge(200).setInterest(350);break;
				}
				ln.save(); 
				
				u.setChecks(S.FCHECK_PROCESS).setIsLoan(1).update();
				
				renderJson(Json.ok("申请成功！"));
			}else {
				renderJson(Json.error("仍有进行中的订单！"));
			}
		}else {
			renderJson(Json.error("用户信息未完善！"));
		}
	}

	/**
	 * 手机估价
	 * @throws Exception
	 */
	public void evaluate() throws Exception { 
		int amt = 1000;
		/**String phone = getPara("phone");
		switch(phone) {
		case "iPhone 6": amt=1000;break;
			case "iPhone 6s":amt=1000;break;
			case "iPhone 6 plus":amt=1200;break;
			case "iPhone 6s plus":amt=1200;break;
			case "iPhone 7":amt=1500;break;
			case "iPhone 7 plus":amt=1500;break;
			case "iPhone 8":amt=2000;break;
			case "iPhone 8 plus":amt=2200;break;
			case "iPhone X":amt=2500;break;
		}*/
		renderJson(Json.ok("操作成功！",amt));
	}
	
	/**
	 * 审核申请记录
	 */ 
	public void check() { 
		Loan ln = Loan.dao.findById(getParaToInt("id"));
		User u = User.dao.findById(ln.getUserId());
		if(Str.eq(S.PASS, u.getInfoVerifyStatus()) && Str.eq(S.PASS, u.getCardVerifyStatus()) 
			&& Str.eq(S.PASS, u.getCardVerifyStatus())  && Str.eq(S.PASS, u.getServiceVerifyStatus())){
			if(ln!=null && (Str.eq(S.VERIFY, ln.getStatus()) || Str.eq(S.PAYING, ln.getStatus()))) {
				if(Str.eq(S.REJECT, getPara("status"))) {
					u.setReason(getPara("reason")).setChecks(S.SCHECK_REJECT);
				}else {
					ln.setAmount(getParaToInt("amount")).setInterest(getParaToInt("interest")).setPledge(getParaToInt("amount")/5).setDay(getParaToInt("day"));
					u.setChecks(S.SCHECK_SUCCESS);
				}
				ln.setStatus(getPara("status")).setReason(getPara("reason")).setCheckTime(new Date()).update();
				u.update();
				renderJson(Json.ok("操作成功！"));
			}else {
				renderJson(Json.error("申请记录状态不正确！"));
			}
		}else {
			renderJson(Json.error("用户信息未审核！"));
		}
	}

	public void modify() { 
		Loan ln = Loan.dao.findById(getParaToInt("id"));
		ln.setAmount(getParaToInt("amount"));
		ln.setInterest(getParaToInt("interest"));
		ln.setPledge(getParaToInt("pledge"));
		ln.update();
		renderJson(Json.ok("操作成功！"));
	}
	
	/**
	 * 进行打款
	 */ 
	public void remittance() { 
		Loan ln = Loan.dao.findById(getParaToInt("id"));
		if(ln!=null && Str.eq(S.PAYING, ln.getStatus())) {
			
			// 更新打款信息
			Date now = new Date(); 
			ln.setStatus(S.REPAY_PROCESS);
			ln.setRemittance(getPara("remittance"));
			ln.setRemittanceTime(new Date());
			ln.setStartTime(now);
			
			// 开始生成还款计划
			int period = ln.getDay()/7;
			User u = User.dao.findById(ln.getUserId());
			double total = 0.0;
			double amt = 0.0;
			Date last = new Date();
			List<Repay> repays = new ArrayList<Repay>();
			for(int i=1;i<=period;i++) {
				Repay rp = new Repay();
				rp.setLoanId(ln.getId());
				rp.setUserId(u.getId());
				rp.setMobile(u.getMobile());
				rp.setRealName(u.getRealName());
				rp.setPeriod(period);
				rp.setApplyPeriod(i);
				rp.setInterest(Double.valueOf(ln.getInterest()));
				rp.setCreateTime(now);
				rp.setStatus(S.REPAY_PROCESS);
				rp.setCid(ln.getCid());
				int adjust = i==1?6:i*7-1;
				String repayTime = DateUtil.adjust(now, adjust, DateUtil.DATE_DEFAULT_FORMAT)+" 23:59:59";
				rp.setRepayTime(DateUtil.parse(repayTime));
				if(rp.getApplyPeriod()==rp.getPeriod()) { 
					rp.setAmount(ln.getAmount()-ln.getPledge());
					rp.setPledge(ln.getPledge());
					last = rp.getRepayTime();
				}else {
					rp.setAmount(0);
					rp.setPledge(0);
				}
				rp.setPeriodTotal(rp.getAmount()+rp.getInterest());
				rp.save();
				repays.add(rp);
				
				total += rp.getPeriodTotal();
				amt += rp.getAmount();
			}		
			
			// 刷新总额
			for(Repay rp : repays) {
				rp.setTotal(Money.format(total)).update();
			}	
			
			ln.setEndTime(last).update();
			
			InvestLogService.build("放款", InvestLogType.LOAN, amt, u.getId(),"放款");
			
			renderJson(Json.error("操作成功！"));
		}else {
			renderJson(Json.error("申请记录状态不正确！"));
		}
	}
	
	/**
	 * 我的记录列表
	 */ 
	public void myList() { 
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String, String> params = Data.flat(getParaMap());
		params.put("userId", String.valueOf(u.getId()));
		Page<Loan> p = loan.list(page,size,params,"create_time desc");
		p.getList().forEach(n->{
			n.setReason("").update();
		});
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}
	
	/**
	 * 复审列表
	 */ 
	public void review() { 
		User u = getAttr("user");
		String mobile = getPara("mobile");
		String checks = getPara("checks");
		String realName = getPara("realName");
		String createTimeStart = getPara("createTimeStart");
		String createTimeEnd = getPara("createTimeEnd");
		SqlPara sqlPara = new SqlPara();
		String where = "select l.*,u.mobile,u.real_name,u.checks,u.reason,u.cname,u.cert_num from loan l left join user u on l.user_id=u.id where l.status='审核中' ";
		if(u.getCid()>1) {  
			sqlPara.addPara(String.valueOf(u.getCid()));
			where += " and u.cid=? ";
		}
		if(Str.nb(checks)) {
			sqlPara.addPara(checks);
			where += " and u.checks=? ";
		}
		if(Str.nb(mobile)) {
			sqlPara.addPara(mobile);
			where += " and u.mobile=? ";
		}
		if(Str.nb(realName)) {
			sqlPara.addPara(realName);
			where += " and u.real_name=? ";
		}
		if(Str.nb(createTimeStart) && Str.nb(createTimeEnd)) {
			sqlPara.addPara(createTimeStart);
			where += " and l.create_time>=? ";
			sqlPara.addPara(createTimeEnd);
			where += " and l.create_time<=? ";
		}
		sqlPara.setSql(where+="order by l.create_time desc");
		System.out.println(sqlPara);
		Page<Loan> p = Loan.dao.paginate(getParaToInt("page",1), getParaToInt("size",10), sqlPara);
		for(Loan ln : p.getList()) {
			ln.put("count", loan.count(ln.getUserId()));
		}
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}
	
	/**
	 * 销售记录列表
	 */ 
	public void list() { 
		int cid = getAttrForInt("cid");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String,String> params = Data.flat(getParaMap());
		if(cid>1) {
			params.put("cid", String.valueOf(cid));
		} 
		Page<Loan> p = loan.list(page,size,params,getPara("orderBy"," create_time desc"));

		for(Loan ln : p.getList()) {
			if(Str.eq(S.REPAY_ADVANCE, getPara("status"))) {
				List<Repay> list = repay.findRepayByLoan(ln.getId(), S.REPAY_ADVANCE);
				double total = 0;
				double periodTotal = 0;
				for(Repay rp : list) {
					total = rp.getTotal();
					periodTotal += rp.getPeriodTotal();
					ln.put("repay_time", rp.getRepayTime());
				}
				ln.put("total", total);
				ln.put("period_total", periodTotal);
			}
			User u = User.dao.findById(ln.getUserId());
			u.put("count", loan.count(u.getId()));
			ln.put("user", u);
		}
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}
	
	/**
	 * 根据ID获取信息
	 * @throws Exception 
	 */
	public void info() throws Exception {	
		Loan ln = Loan.dao.findById(getParaToInt("id",0));
		ln.put("user", User.dao.findById(ln.getUserId()));
		ln.getRapays();
		renderJson(Json.ok("信息获取成功！", ln));
	}
}
 